package com.common.tag;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import com.common.util.BeanUtils;
import com.common.util.StringUtil;

public class ObjMapping extends BaseTag {

	private String beanName;
	private String value;
	private Object items;
	
	private String keyName;
	private String valName;
	
	private String nullStr="";
	
	public String getNullStr() {
		return nullStr;
	}
	public void setNullStr(String nullStr) {
		this.nullStr = nullStr;
	}
	public String getKeyName() {
		return keyName;
	}
	public void setKeyName(String keyName) {
		this.keyName = keyName;
	}
	public String getValName() {
		return valName;
	}
	public void setValName(String valName) {
		this.valName = valName;
	}
	public Object getItems() {
		return items;
	}
	public void setItems(Object items) {
		this.items = items;
	}
	public String getBeanName() {
		return beanName;
	}
	public void setBeanName(String beanName) {
		this.beanName = beanName;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	@Override
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		StringBuilder outStr = new StringBuilder("");
		Map map = null;
		if(beanName!=null&&getServletContext().getAttribute(beanName)!=null){
			map = (Map) getServletContext().getAttribute(beanName);
		}else if(items!=null){
			if(items instanceof Collection){
				Collection c = (Collection) items;
				map = new HashMap();
				Iterator iter = c.iterator();
				while(iter.hasNext()){
					Object o = iter.next();
					map.put(BeanUtils.forceGetProperty(o, keyName),BeanUtils.forceGetProperty(o, valName));
				}
			}else if(items instanceof Map){
				map = (Map) items;
			}
		}
			
		
		if(map!=null){
		if(!StringUtil.isBlank(value)){
			if(map.get(value)!=null){
				outStr.append(map.get(value));
			}else{
				outStr.append(nullStr);
			}
			
		}else{
			outStr.append(nullStr);
		}
		}else{
			outStr.append(nullStr);
		}
		try {
			out.write(outStr.toString());
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		return SKIP_PAGE;
	}
	
}
